import {songExist, downloadSong, listFolder} from "../../utils/FileDownloadUtil"
import {formatTimeBySec} from "../../utils/util"

const app = getApp()
Component({
  properties: {
    item: {
      type: Object,
      value: null,
      observer(newVal, oldVal){
        const _this = this
        const item = this.properties.item;
        this.setData({
          duration: item.metadata.duration,
          durationStr: formatTimeBySec(item.metadata.duration)
        })
      }
    }
  },
  data: {
    isLoading: false,
    loadingText: "加载中",
    musicLoaded: false,
    isPlaying: false,
    currentTime: 0,
    duration: 0,
    currentTimeStr: '00:00',
    durationStr: '00:00',
  },

  lifetimes: {
    detached() {
      this.audio?.destroy()
    }
  },
  methods: {
    createAudio(url) {
      if (this.audio)
        return
      this.audio = wx.createInnerAudioContext()
      this.audio.src = url
      this.audio.autoplay = false

      this.audio.onPlay(() => {
        this.setData({
          isPlaying: true
        })
      })

      this.audio.onPause(() => {
        this.setData({
          isPlaying: false
        })
      })

      this.audio.onTimeUpdate(() => {
        this.setData({
          currentTime: this.audio.currentTime,
          duration: this.audio.duration,
          currentTimeStr: formatTimeBySec(this.audio.currentTime),
          durationStr: formatTimeBySec(this.audio.duration),
        })
      })
    },
    async loadSong(e) {
      const key = this.properties.item.id;

      if (!songExist(key)) {
        this.setData({
          isLoading: true,
        })

        await downloadSong(this.data.item, (progress) => {
          this.setData({
            loadingText: progress
          })
        })

        this.setData({
          isLoading: false
        })
      }
      const parser = app.globalData.songs[key].parser
      const targetPath = app.globalData.songs[key].path
      const songFilePath = targetPath + encodeURI(parser.getSongFileName())
      // 5. Play song here.
      this.setData({
        isMusicLoaded: true,
        fullMusicPath: songFilePath
      });
    },

    async togglePlay() {
      await this.loadSong();
      this.createAudio(this.data.fullMusicPath)
      if (this.data.isPlaying) {
        this.audio.pause()
      } else {
        listFolder(app.globalData.songs[this.properties.item.id].path)
        this.audio.play()
      }
    },

    onSliderChange(e) {
      this.audio.seek(e.detail.value)
    }
  }
})